package web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import pojo.TableAttributeDTO;
import pojo.TransmessionVO;
import pojo.Ze42DTO;
import utils.JsonUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhuozhengsoft.pageoffice.DocumentOpenType;
import com.zhuozhengsoft.pageoffice.FileMakerCtrl;
import com.zhuozhengsoft.pageoffice.PDFCtrl;
import com.zhuozhengsoft.pageoffice.ThemeType;
import com.zhuozhengsoft.pageoffice.wordwriter.DataRegion;
import com.zhuozhengsoft.pageoffice.wordwriter.Table;
import com.zhuozhengsoft.pageoffice.wordwriter.WordDocument;

@Controller
public class WordToPDFAndView extends HttpServlet {
	private static final long serialVersionUID = -758686623642845302L;

	@RequestMapping("wordToPDF")
	public String wordToPDF(HttpServletRequest request, HttpServletResponse response) {
		ObjectMapper jackson = new ObjectMapper();
		Ze42DTO ze42dto = JsonUtils.createData();
		TransmessionVO transmessionVO = new TransmessionVO();
		try {
			transmessionVO = jackson.readValue(ze42dto.getJsonData(), TransmessionVO.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		FileMakerCtrl fmCtrl = new FileMakerCtrl(request);
		fmCtrl.setServerPage(request.getContextPath() + "/poserver.zz");
		WordDocument doc = new WordDocument();

		// 给数据区域赋值，即把数据填充到模板中相应的位置
		doc.openDataRegion("company").setValue("北京卓正志远软件有限公司  ");

		JsonNode node;
		int index = 1;
		try {
			node = jackson.readTree(ze42dto.getJsonData());
			
			if (node.isObject()) {
				Iterator<Entry<String, JsonNode>> it = node.fields();
				while (it.hasNext()) {
					Entry<String, JsonNode> entry = it.next();
					if (entry.getValue().isValueNode()) {// 对象值为普通ValueNode
						doc.openDataRegion(entry.getKey()).setValue(entry.getValue().toString());
					}

					if (entry.getValue().isObject()) {// 对象值为Object
						Iterator<Entry<String, JsonNode>> it2 = entry.getValue().fields();
						DataRegion dataRegion = doc.openDataRegion(entry.getKey());
						Table table = dataRegion.openTable(index);
						while (it2.hasNext()) {
							Entry<String, JsonNode> entry2 = it2.next();
							// 取表格插入行号
							List<TableAttributeDTO> tableAttributeDTOs = transmessionVO.getTableAttributes();
							TableAttributeDTO attributeDTO = new TableAttributeDTO();
							if (tableAttributeDTOs != null) {
								attributeDTO = tableAttributeDTOs.get(index - 1);
							}
							/*
							 * int startRowNumber = 2;//默认从表格第二行还是插入数据
							 * if(attributeDTO.getStartRowNumber() != null){
							 * startRowNumber =
							 * attributeDTO.getStartRowNumber(); }
							 */
							if (attributeDTO.getTotalColumnNumber() == null) {
								System.out.println("表格总共列数[totalColumnNumber]为空");
							}
							int insertRowNumber = Integer.valueOf(entry2.getKey());
							table.insertRowAfter(table.openCellRC(insertRowNumber - 1,attributeDTO.getTotalColumnNumber()));

							String[] strs = entry2.getValue().toString().split(",");
							for (int i = 0; i < strs.length; i++) {// 默认从第一列开始插入
								String str = strs[i].replace("\"", "");
								table.openCellRC(insertRowNumber, i + 1).setValue(str != null ? str : "");
							}
						}
						index++;
					}

					if (entry.getValue().isArray()) {
						Iterator<JsonNode> it3 = node.iterator();

					}
				}
			} else {
				System.out.println("传入数据格式非json");
			}
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		fmCtrl.setSaveFilePage("savefile.do");
		fmCtrl.setWriter(doc);
		fmCtrl.setJsFunction_OnProgressComplete("OnProgressComplete()");
		fmCtrl.fillDocumentAsPDF("doc/template.doc", DocumentOpenType.Word,"tmp.pdf");
		fmCtrl.setTagId("FileMakerCtrl1");
		return "wordToPDF2";

	}

	@RequestMapping("viewPDF")
	public String viewPDF(HttpServletRequest request, HttpServletResponse response) {
		// 按键说明：光标键、Home、End、PageUp、PageDown可用来移动或翻页；数字键盘+、-用来放大缩小；数字键盘/、*用来旋转页面。
		PDFCtrl pdfCtrl = new PDFCtrl(request);// 定义PDFCtrl控件对象
		pdfCtrl.setServerPage(request.getContextPath() + "/poserver.zz"); // 设置服务器页面
		pdfCtrl.setTheme(ThemeType.CustomStyle);// 设置主题样式
		// 添加自定义按钮
		pdfCtrl.addCustomToolButton("打印", "Print()", 6);
		pdfCtrl.addCustomToolButton("-", "", 0);
		pdfCtrl.addCustomToolButton("实际大小", "SetPageReal()", 16);
		pdfCtrl.addCustomToolButton("适合页面", "SetPageFit()", 17);
		pdfCtrl.addCustomToolButton("适合宽度", "SetPageWidth()", 18);
		pdfCtrl.addCustomToolButton("-", "", 0);
		pdfCtrl.addCustomToolButton("首页", "FirstPage()", 8);
		pdfCtrl.addCustomToolButton("上一页", "PreviousPage()", 9);
		pdfCtrl.addCustomToolButton("下一页", "NextPage()", 10);
		pdfCtrl.addCustomToolButton("尾页", "LastPage()", 11);
		pdfCtrl.addCustomToolButton("-", "", 0);
		pdfCtrl.addCustomToolButton("左转", "RotateLeft()", 12);
		pdfCtrl.addCustomToolButton("右转", "RotateRight()", 13);
		pdfCtrl.addCustomToolButton("-", "", 0);
		pdfCtrl.addCustomToolButton("放大", "ZoomIn()", 14);
		pdfCtrl.addCustomToolButton("缩小", "ZoomOut()", 15);
		pdfCtrl.addCustomToolButton("-", "", 0);
		pdfCtrl.addCustomToolButton("全屏", "SwitchFullScreen()", 4);
		// 设置禁止拷贝
		pdfCtrl.setAllowCopy(false);

		String fileName = "blank.pdf";// 定义文件名称
		pdfCtrl.webOpen("doc/" + fileName);// 打开文件
		pdfCtrl.setTagId("PDFCtrl1");
		return "OpenPDF";
	}
}
